package com.mobilesalon.tools;

import java.text.DateFormat;
import java.text.ParseException;
import java.util.Date;

import android.content.Context;
import android.database.Cursor;
import android.util.Log;
import android.view.View;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;

import com.mobilesalon.R;

public class MyCursorAdapter extends SimpleCursorAdapter {
	private static final String TAG = MyCursorAdapter.class.getName();

	public MyCursorAdapter(Context context, int layout, Cursor c, String[] from, int[] to) {
		super(context, layout, c, from, to);
	}

	/**
	 * 
	 * @param columnFrom
	 * @param to
	 * @param dateFormat
	 */
	public void addDateFormatFromTimeStamp(final String  columnFrom, final int to,
			final DateFormat dateFormat) {
		this.setViewBinder(new ViewBinder() {
			public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
				if (columnIndex == cursor.getColumnIndex(columnFrom)) {
					TextView textView = (TextView) view
							.findViewById(R.id.service_client_appointment_row_time);
					Date date = new Date();
					try {
						date = DateTools.TIMESTAMP_DATEFORMAT.parse(cursor
								.getString(columnIndex));
					} catch (ParseException e) {
						e.printStackTrace();
						Log.e(TAG, "Cannot parse date");
					}
					textView.setText(dateFormat.format(date));
					return true;
				}
				return false;
			}
		});

	}

	/**
	 * convet milisecond calendar representation to a string
	 * 
	 * @param columnFrom
	 * @param to
	 * @param dateFormat
	 */
	public void addDateFormatFromLong(final String columnFrom, final int to,
			final DateFormat dateFormat) {
		this.setViewBinder(new ViewBinder() {
			public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
				if (columnIndex == cursor.getColumnIndex(columnFrom)) {
					TextView textView = (TextView) view
							.findViewById(R.id.service_client_appointment_row_time);
					Date date = new Date(cursor.getLong(columnIndex));
					textView.setText(dateFormat.format(date));
					return true;
				}
				return false;
			}
		});

	}
}
